using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework.Content;
using Phoenix.Xna.Framework.Graphics.Animation;
using Phoenix.Xna.Framework.Reflection;

namespace Phoenix.Xna.Framework.ContentPipeline.Animation
{
    public class AnimationClipReader : ContentTypeReader<AnimationClip>
    {
        protected override AnimationClip Read(ContentReader input, AnimationClip existingInstance)
        {
            string animationName = input.ReadString();
            TimeSpan animationDuration = input.ReadObject<TimeSpan>();
            Dictionary<string, AnimationChannel> animationChannelDictionary = new Dictionary<string, AnimationChannel>();
            int animationChannels = input.ReadInt32();

            for (int i = 0; i < animationChannels; i++)
            {
                string channelName = input.ReadString();
                int channelKeyframes = input.ReadInt32();
                List<AnimationChannelKeyframe> keyframeList = new List<AnimationChannelKeyframe>(channelKeyframes);

                for (int j = 0; j < channelKeyframes; j++)
                {
                    TimeSpan keyframeTime = input.ReadObject<TimeSpan>();
                    Pose keyframePose;
                    keyframePose.Translation = input.ReadVector3();
                    keyframePose.Orientation = input.ReadQuaternion();
                    keyframePose.Scale = input.ReadVector3();
                    keyframeList.Add(new AnimationChannelKeyframe(keyframeTime, keyframePose));
                }

                AnimationChannel animationChannel = new AnimationChannel(keyframeList);
                animationChannelDictionary.Add(channelName, animationChannel);
            }

            AnimationClip ac = ReflectionHelper.CreateInstance<AnimationClip>();
            ReflectionHelper.SetProperty<AnimationClip>(ac, "Channels", new AnimationChannelDictionary(animationChannelDictionary));
            ReflectionHelper.SetProperty<AnimationClip>(ac, "Name", animationName);
            ReflectionHelper.SetProperty<AnimationClip>(ac, "Duration", animationDuration);

            if (existingInstance == null)
            {
                existingInstance = ReflectionHelper.CreateInstance<AnimationClip>();
            }

            if (ac != null)
            {
                existingInstance = ac;
            }

            return ac;
        }
    }
}